<?php

namespace app\services\eid;

use think\facade\Db;
use think\facade\Env;
use think\facade\Cache;
use think\facade\Event;
use think\facade\Snowflake;
use app\services\BaseServices;
use crmeb\services\CacheService;
use app\services\user\UserServices;
use app\dao\worker\RepairWorkerDao;
use crmeb\exceptions\AdminException;
use think\db\exception\{DataNotFoundException, DbException, ModelNotFoundException};
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Faceid\V20180301\FaceidClient;
use TencentCloud\Faceid\V20180301\Models\GetEidResultRequest;
use Rtgm\sm\RtSm2;
use Rtgm\sm\RtSm4;

/**
 *
 * Class UserServices
 * @package app\services\eid
 * @mixin RepairWorkerDao
 */
class GetEidResultServices extends BaseServices
{
    /**
     * UserServices constructor.
     * @param RepairWorkerDao $dao
     */
    public function __construct(RepairWorkerDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 注册维修师傅账号
     * @param string $EidToken
     * @param int $userId
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function registerWorker(string $EidToken, int $userId)
    {
        $result = $this->getEidResult($EidToken, $userId);

        // 开始注册师傅账号
        return $this->transaction(function () use ($EidToken, $userId, $result) {
            /** @var UserServices $userServices */
            $userServices = app()->make(UserServices::class);

            if (!$userServices->update($userId, ['eid_token' => $EidToken, 'name' => $result['data']['name'], 'card_id' => $result['data']['idnum']])) {
                throw new AdminException('网络错误请稍后再试！');
            }

            /** @var RepairWorkerDao $repairWorker */
            $repairWorker = $this->dao->getOne(['card_id' => $result['data']['idnum']]);

            if ($repairWorker) {
                throw new AdminException('维修师傅账号已经注册过！');
            }

            $res = $this->dao->save([
                'uid' => $userId,
                'name' => $result['data']['name'],
                'card_id' => $result['data']['idnum'],
                'user_type' => 1, // 师傅类型;1:普通师傅;2:高级师傅
                'make_code' => makeWorkerCode(), // 自动生成推广码
            ]);

            if (!$res) {
                throw new AdminException('网络错误请稍后再试！');
            }

            return true;
        });
    }

    /**
     * 获取E证通结果信息
     * @param string $EidToken
     * @param int $userId
     * @return array
     */
    public function getEidResult(string $EidToken, int $userId)
    {
        if (!$EidToken) {
            throw new AdminException('请传入EidToken');
        }

        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            $cred = new Credential(Env::get('TencentCloud.secretId'), Env::get('TencentCloud.secretKey'));
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("faceid.tencentcloudapi.com");

            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            $client = new FaceidClient($cred, "", $clientProfile);

            // 实例化一个请求对象,每个接口都会对应一个request对象
            $req = new GetEidResultRequest();

            $params = array(
                "EidToken" => $EidToken
            );
            $req->fromJsonString(json_encode($params));

            // 返回的resp是一个GetEidResultResponse的实例，与请求对象对应
            $resp = $client->GetEidResult($req);

            $respData = json_decode($resp->toJsonString(), true);

            $PrivateKey = Env::get('EID.PrivateKey');
            $DesKey = $respData['EidInfo']['DesKey'];
            $UserInfo = $respData['EidInfo']['UserInfo'];


            $url = Env::get('EID.go_url');
            $argument = [
                'DesKey' => $DesKey,
                'PrivateKey' => $PrivateKey,
                'UserInfo' => $UserInfo
            ];

            $result = http_post($argument, $url);

            if (isset($result['code']) && $result['code'] == 200) {

                $return = [
                    'userId' => $userId,
                    'EidToken' => $EidToken,
                    'data' => $result['data'],
                    'respData' => $respData
                ];
                return $return;
            } else {
                throw new AdminException('go解密接口出错');
            }

        } catch (TencentCloudSDKException $e) {
//            echo $e;
            throw new AdminException($e);
        }
    }

//    /**
//     * 获取E证通结果信息
//     * @param string $EidToken
//     * @return mixed
//     */
//    public function getEidResult(string $EidToken)
//    {
//        if (!$EidToken) {
//            throw new AdminException('请传入EidToken');
//        }
//
//        try {
//            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
//            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
//            $cred = new Credential(Env::get('TencentCloud.secretId'), Env::get('TencentCloud.secretKey'));
//            // 实例化一个http选项，可选的，没有特殊需求可以跳过
//            $httpProfile = new HttpProfile();
//            $httpProfile->setEndpoint("faceid.tencentcloudapi.com");
//
//            // 实例化一个client选项，可选的，没有特殊需求可以跳过
//            $clientProfile = new ClientProfile();
//            $clientProfile->setHttpProfile($httpProfile);
//            // 实例化要请求产品的client对象,clientProfile是可选的
//            $client = new FaceidClient($cred, "", $clientProfile);
//
//            // 实例化一个请求对象,每个接口都会对应一个request对象
//            $req = new GetEidResultRequest();
//
//            $params = array(
//                "EidToken" => $EidToken
//            );
//            $req->fromJsonString(json_encode($params));
//
//            // 返回的resp是一个GetEidResultResponse的实例，与请求对象对应
//            $resp = $client->GetEidResult($req);
//
//            // 输出json格式的字符串回包
////            print_r($resp->toJsonString());
//
//
//            $privateKey = 'ece6e44b4e98bf8f78c3944cfae63d1ccc2dc0a21ff28aef6db5b94a3f645295';
//            $desKey = 'BKMx3pULlY8YcmKQ96TzGiHWYwdALLcb50nnuGbvqasMrUBXaflk4WGhfunjRoDklVXIgF2fHrfhyhpVXcVIBR5nXY/bOAuLheLEPCkCrSxO2LJyB6Sz1+DeG7BsKEcC+zI7BsAJ/Vzn+FpVMgv4IMo=';
//            $userInfo = '0MWVv7/viJe1MNgNHIuPqmzxUvK+XIs59RDZvhx9UNQrlPb6tG7VOUX2ew4JB3wnaa6NQraF4C/J5xmS3LZxYg==';
//
//            $desKey = bin2hex(base64_decode($desKey));
////            $desKey = base64_decode($desKey);
//
////            halt($desKey);
//
//            $sm2    = new RtSm2($privateKey);
////            halt($sm2);
//
//            $sm4KeyBytes = $sm2->doDecrypt($desKey,$privateKey);
////            halt($sm4KeyBytes);
//
//            $sm4    = new RtSm4($sm4KeyBytes);
//            $json = $sm4->decrypt(bin2hex(base64_decode($userInfo)));
//            halt($json);
//
//
//
//            $json = $sm4->decrypt($sm4KeyBytes,'sm4-cbc', $sm4KeyBytes, 'base64');
////            $json = $sm4->decrypt($sm4KeyBytes, $type = 'sm4-cbc', $iv = $sm4KeyBytes, $formatInput = 'base64');
//
//            halt($json);
//            $data = json_decode($json, true);
//
//
//
//
//            return json_decode($resp->toJsonString(), true);
//        } catch (TencentCloudSDKException $e) {
////            echo $e;
//            throw new AdminException($e);
//        }
//    }
}
